import Styles from './index.module.less'
import Link from "next/link";
import { useRouter } from "next/router";
import { Button } from '@mantine/core';
import { useCallback, useEffect, useState } from 'react';
import { Modal } from '@mantine/core';
import dynamic from 'next/dynamic';
import toast from 'react-hot-toast';
import { ClientAxios } from '@/common/useAxios';
const Login = dynamic(()=>import('../login/index'), { ssr: false })
function Nav(){
    const [useInfo,setUserInfo]= useState({})
    const [showLogin,setShowLogin] = useState(false)
    const router = useRouter()
    // 获取当前页面的pathname
    const pathname = router.pathname;
    useEffect(()=>{
        ClientAxios.post('/user/information').then(({data:res})=>{
            if(res.code === 1){
                setUserInfo(res.data)
            }
        })
    },[])
    const tuichu = useCallback(()=>{
        ClientAxios.post('/user/loginout').then(({data:res})=>{
            if(res.code == 1){
                toast(res.msg);
                setTimeout(()=>{
                    location = '/'
                },1000)
            }
        })
    },[])
    return (
        <div className={'nav '+Styles.nav}>
            <div className='box'>
                <div className='l'>
                    <Button.Group>
                        <Link href="/">
                            <Button variant="default">首页</Button>
                        </Link>
                        <Link href="/list">
                            <Button variant="default">列表页</Button>
                        </Link>
                    </Button.Group>
                </div>
                <div className='r'>
                    <Button.Group>
                        {
                            useInfo.account && <>
                                <Link href="/create">
                                    <Button variant="default">写文章</Button>
                                </Link>
                                <Button variant="default">用户:{useInfo.nickname}</Button>
                                <Button variant="default" onClick={tuichu}>退出登录</Button>
                            </>
                        }
                        {
                            ((pathname !== '/login') && !useInfo.account) && <Button onClick={()=>{setShowLogin(true)}} variant="default">登录/注册</Button>
                        }
                    </Button.Group>
                </div>
            </div>
            <Modal opened={showLogin} 
                onClose={()=>{setShowLogin(false)}} 
                title=""
                size="sm"
                centered
            >
                <Login />
            </Modal>
        </div>
    )
}
export default Nav